package org.example.springbootrabbitmq.confirm;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ConfirmConfig {

    public static final String EXCHANGE_NAME = "confirm_exchange";
    static final String QUEUE_NAME = "confirm_queue";
    static final String ROUTING_KEY = "confirm_routing_key";

    // 备份交换机相关配置
    static final String BACKUP_EXCHANGE = "backup_exchange";
    static final String BACKUP_QUEUE = "backup_queue";
    static final String ALARM_QUEUE = "alarm_queue";
    static final String BACKUP_ROUTING_KEY = "backup_routing_key";
    static final String ALARM_ROUTING_KEY = "alarm_routing_key";

    @Bean("confirm_exchange")
    public DirectExchange confirmExchange() {
        // 普通创建
//        return new DirectExchange(EXCHANGE_NAME);
        // 交换机增加备份交换机配置参数，需要通过ExchangeBuilder 进行构建
        return ExchangeBuilder.directExchange(EXCHANGE_NAME).durable(true).withArgument("alternate-exchange", BACKUP_EXCHANGE).build();
    }

    @Bean("confirm_queue")
    public Queue confirmQueue() {
        return new Queue(QUEUE_NAME);
    }

    @Bean("confirm_binding")
    public Binding confirmBinding(@Qualifier("confirm_exchange") DirectExchange confirmExchange,
                                  @Qualifier("confirm_queue") Queue confirmQueue) {
        return new Binding(confirmQueue.getName(), Binding.DestinationType.QUEUE, confirmExchange.getName(), ROUTING_KEY, null);
    }

    @Bean("backup_exchange")
    public FanoutExchange backupExchange() {
        return new FanoutExchange(BACKUP_EXCHANGE);
    }

    @Bean("backup_queue")
    public Queue backupQueue() {
        return new Queue(BACKUP_QUEUE);
    }

    @Bean("alarm_queue")
    public Queue alarmQueue() {
        return new Queue(ALARM_QUEUE);
    }

    @Bean("backup_binding")
    public Binding backupBinding(@Qualifier(BACKUP_EXCHANGE) FanoutExchange backupExchange,
                                 @Qualifier(BACKUP_QUEUE) Queue backupQueue) {
        return
            new Binding(backupQueue.getName(), Binding.DestinationType.QUEUE, backupExchange.getName(), BACKUP_ROUTING_KEY, null);
    }

    @Bean("alarm_binding")
    public Binding alarmBinding(@Qualifier(BACKUP_EXCHANGE) FanoutExchange confirmExchange,
                                @Qualifier(ALARM_QUEUE) Queue alarmQueue) {
        return
            new Binding(alarmQueue.getName(), Binding.DestinationType.QUEUE, confirmExchange.getName(), ALARM_ROUTING_KEY, null);
    }

}
